package com.zzy.util;

import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class UtilRedis {

    public static String url = UtilProperties.getConfig("redis.server.url");


    public static void main(String[] args) {
        Jedis jedis =getCon();
        //getAllKey( jedis);
       //getStringVal(jedis,"zzy");
        List<String> list = getListVal(jedis,"site-list",0,10);
        System.out.println(list);
    }

    /**
     * 获取连接
     * @return
     */
    public static Jedis getCon(){
        Jedis jedis = new Jedis(url);
        System.out.println("获取redis连接……");
        return jedis;
    }

    /**
     * 获取 所有的key值
     * @return
     */
    public static List<String> getAllKey(Jedis jedis) {
        List<String> list = new ArrayList<>();
        Set<String> keys = jedis.keys("*");
        Iterator<String> it=keys.iterator() ;
        while(it.hasNext()){
            list.add(it.next());
        }
        System.out.println(list);
        return list;
    }


    /**
     * 获取 key 的 String 值
     * @param key
     * @return
     */
    public static  String getStringVal(Jedis jedis ,String key){
        return jedis.get(key);
    }

    /**
     * 获取 key 的 List 值
     * @param key
     * @return
     */
    public static  List<String> getListVal(Jedis jedis ,String key,int start,int end ){
        List<String> list  = jedis.lrange(key,start,end);
        return list;
    }


    /**
     * 写入 string 值
     * @return
     */
    public static boolean pushString(Jedis jedis ,String key,String val) {
        jedis.set(key, val);
        return  true;
    }


    /**
     * 写入list
     * @param key
     * @param list
     * @return
     */
    public static boolean pushList(Jedis jedis ,String key,List<String> list) {
        if(list!=null){
            for(String o : list){
                jedis.lpush(key, o);
            }
        }
        jedis.lrange("site-list", 0 ,list.size());
        return true;
    }

    /**
     * 删除 key
     * @param key
     * @return
     */
    public static boolean deleteData(Jedis jedis ,String key){
        if (jedis.exists(key)) {
            if (jedis.del(key) == 1) {
                System.out.println("删除成功！");
                return true;
            } else {
                return false;
            }
        } else {
            System.out.println(" Key: "+key+ " 不存在！");
            return false;
        }
    }




}
